﻿using Sidvall.WorkItemManager.Data;
using Sidvall.WorkItemManager.Net.Services.V1;
using System.Threading.Tasks;

namespace Sidvall.WorkItemManager.Workflow.RetryPolicies
{
	public class IntervalRetryPolicyProvider : RetryPolicyProviderBase
	{
		#region Public Members

		public override Task<System.DateTime?> GetNextRetryTimeAsync(IWorkItem item)
		{
			System.DateTime? nextRetry;

			if (item == null)
				throw new System.ArgumentNullException("item");
			if (item.LastWorkItemResultId == null)
				return null;
			if (item.LastWorkItemResultId.Value != WorkItemResultType.Failed)
				return null;

			DeserializeContext();
			if ((this.RetryPolicyContext.MaxRetryCount != null) && (this.RetryPolicyContext.MaxRetryCount <= item.RetryCount))
				return Task.FromResult((System.DateTime?)null);
			nextRetry = System.DateTime.UtcNow.Add(this.RetryPolicyContext.RetryInterval);

			return Task.FromResult(nextRetry);
		}

		#endregion
		#region Private Members

		private IntervalRetryPolicy RetryPolicyContext { get; set; }

		private void DeserializeContext()
		{
			if (!string.IsNullOrWhiteSpace(this.Context))
				this.RetryPolicyContext = Sidvall.Serialization.SerializerManager.Current.Deserialize<IntervalRetryPolicy>(this.Context);
			else
				this.RetryPolicyContext = null;
			if (this.RetryPolicyContext == null)
				throw new System.ArgumentException("Invalid retry policy settings.");
		}

		#endregion
	}
}
